package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mappers.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private BasicClient basicClient;

    //获取预览的发布课程
    public Map preview(Long courseBaseId) {
        //1.判断参数
        if (courseBaseId == null) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //2.查询课程计划信息
        ResponseResult<TeachplanVo> treeNodesResult = teachplanService.treeNodes(courseBaseId);
        TeachplanVo teachplanVo = treeNodesResult.getData();
        //3.创建coursePub课程发布对象
        //3.1向课程发布对象中设置课程信息
        //3.1.1查询课程信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);

        coursePub.setCourseId(courseBase.getId());
        coursePub.setPrice(courseBase.getPrice().longValue());

        coursePub.setMtName(getCategoryName(coursePub.getMt()));
        coursePub.setStName(getCategoryName(coursePub.getSt()));

        //3.2向课程发布对象中设置课程计划信息
        coursePub.setTeachplan(JSON.toJSONString(teachplanVo));
        //3.3向课程发布对象中设置老师信息

        //4.构造返回值
        Map<String, Object> map = new HashMap<>();
        map.put("teachplanNode", teachplanVo);
        map.put("coursePub", coursePub);
        return map;
    }

    //根据id调用basic的feign接口进行查询
    public String getCategoryName(String id) {
        ResponseResult<CategoryVo> result = basicClient.findById(id);
        CategoryVo categoryVo = result.getData();
        return categoryVo.getName();
    }
}
